package com.microframework.boot.visual.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.microframework.base.web.page.PageQuery;
import com.microframework.boot.visual.model.domain.MaterialCategory;
import com.microframework.boot.visual.service.IMaterialCategoryService;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class MaterialCategoryServiceImpl implements IMaterialCategoryService {

	@Override
	public List<MaterialCategory> loadAll(PageQuery<MaterialCategory> pageQuery) {
		try {
			String select = "select * ";
			StringBuilder sqlBuilder = new StringBuilder(select + " FROM " + MaterialCategory.TABLE_NAME + " WHERE 1=1");
			List<Object> params = new ArrayList<>();

			MaterialCategory query = pageQuery.getQuery();
			if (query != null) {
				// 构建查询条件

				if (StringUtils.hasText(query.getName())) {
					sqlBuilder.append(" AND name LIKE ?");
					params.add("%" + query.getName() + "%");
				}

				if (StringUtils.hasText(query.getCode())) {
					sqlBuilder.append(" AND code LIKE ?");
					params.add("%" + query.getCode() + "%");
				}

				if (StringUtils.hasText(query.getParentId())) {
					sqlBuilder.append(" AND parent_id = ?");
					params.add(query.getParentId());
				}

				if (StringUtils.hasText(query.getIsDel())) {
					sqlBuilder.append(" AND is_del = ?");
					params.add(query.getIsDel());
				} else {
					sqlBuilder.append(" AND is_del = ?");
					params.add("0");
				}
			}else {
				sqlBuilder.append(" AND is_del = ?");
				params.add("0");
			}

			// 设置排序
			String orderBy = StringUtils.hasText(pageQuery.getOrderBy()) ? pageQuery.getOrderBy() : " sort";
			String orderDirection = StringUtils.hasText(pageQuery.getOrderDirection()) ? pageQuery.getOrderDirection()
					: " asc ";
			sqlBuilder.append(" ORDER BY " + orderBy + " " + orderDirection);
			
			System.out.println(sqlBuilder.toString());
			List<MaterialCategory> materialCategorys = MaterialCategory.dao.find(sqlBuilder.toString(), params.toArray());
			return buildTree(materialCategorys);
		} catch (Exception e) {
			log.error("查询异常{}", e.getMessage());
			return new LinkedList<MaterialCategory>();
		}
	}

	public List<MaterialCategory> buildTree(List<MaterialCategory> nodes) {
		// 1. 创建快速查找映射表
		Map<String, MaterialCategory> nodeMap = new HashMap<>();
		Map<String, List<MaterialCategory>> parentChildMap = new HashMap<>();

		// 2. 构建索引
		for (MaterialCategory node : nodes) {
			String nodeId = node.getId();
			String parentId = node.getParentId();

			// 存储节点映射
			nodeMap.put(nodeId, node);

			// 构建父子关系映射
			parentChildMap.computeIfAbsent(parentId, k -> new ArrayList<>()).add(node);
		}

		// 3. 识别根节点（没有父节点或父节点不存在）
		List<MaterialCategory> roots = new ArrayList<>();
		for (MaterialCategory node : nodes) {
			String parentId = node.getParentId();

			// 根节点条件：父节点为空、不存在或指向自身（根据业务需求调整）
			if (parentId == null || !nodeMap.containsKey(parentId) || parentId.equals(node.getId())) {
				roots.add(node);
			}
		}

		// 4. 递归构建树形结构
		roots.forEach(root -> buildTreeRecursive(root, parentChildMap));

		return roots;
	}

	private void buildTreeRecursive(MaterialCategory node, Map<String, List<MaterialCategory>> parentChildMap) {
		String nodeId = node.getId();
		List<MaterialCategory> children = parentChildMap.get(nodeId);

		if (children != null && !children.isEmpty()) {
			// 设置子节点并继续递归构建
			node.setChildren(children);
			children.forEach(child -> buildTreeRecursive(child, parentChildMap));
		}
	}
}
